package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.ExtendedBounds;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalDateHistogram;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @ClassName: AggsTvsSearch
 * @author: BANG
 * @Date: 2020/01/15 13:56
 * @Version: 1.0
 * @Modified By:
 * @Desc:
 *
 * GET /tvs/sales/_search
 * {
 *   "size": 0,
 *   "aggs": {
 *     "group_by_sold_date": {
 *       "date_histogram": {
 *         "field": "sold_date",
 *         "interval": "quarter",
 *         "format": "yyyy-MM-dd",
 *         "min_doc_count": 0,
 *         "extended_bounds": {
 *           "min": "2016-01-01",
 *           "max": "2017-12-31"
 *         }
 *       },
 *       "aggs": {
 *         "group_by_brand": {
 *           "terms": {
 *             "field": "brand"
 *           },
 *           "aggs": {
 *             "sum_price": {
 *               "sum": {
 *                 "field": "price"
 *               }
 *             }
 *           }
 *         },
 *         "total_sum_price": {
 *           "sum": {
 *             "field": "price"
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 */
public class DateHistogramTvsSearch2 {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("tvs").setTypes("sales")
                .addAggregation(AggregationBuilders.dateHistogram("group_by_sold_date")
                                .field("sold_date")
                                .format("yyyy-MM-dd")
                                .minDocCount(0L)
                                .dateHistogramInterval(DateHistogramInterval.QUARTER)
                                .extendedBounds(new ExtendedBounds("2016-01-01","2017-12-31"))
                                .subAggregation(AggregationBuilders.terms("group_by_brand").field("brand")
                                                .subAggregation(AggregationBuilders.sum("sum_price").field("price"))
                                                )
                                .subAggregation(AggregationBuilders.sum("total_sum_price").field("price"))
                                )
                .setSize(0)
                .get();


        Aggregations aggregations = searchResponse.getAggregations();
        InternalDateHistogram dateHistogram = aggregations.get("group_by_sold_date");
        List<Histogram.Bucket> buckets = dateHistogram.getBuckets();
        for (Histogram.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            System.err.println(keyAsString+"=="+docCount);
            Aggregations bucketAggregations = bucket.getAggregations();
            InternalSum total_sum_price = bucketAggregations.get("total_sum_price");
            System.err.println("total_sum_price"+"=="+total_sum_price.getValueAsString());

            StringTerms group_by_brand = bucketAggregations.get("group_by_brand");
            List<Terms.Bucket> group_by_brandBuckets = group_by_brand.getBuckets();
            for (Terms.Bucket byBrandBucket : group_by_brandBuckets) {
                System.err.println(byBrandBucket.getKeyAsString()+"=="+byBrandBucket.getDocCount());
                InternalSum sum_price = byBrandBucket.getAggregations().get("sum_price");
                System.err.println("sum_price:"+sum_price.getValueAsString());
            }
            System.err.println("======================================================");

        }
        client.close();

    }
}
